package ltd.handler;

import java.util.Date;


import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import ltd.bean.Session;
import ltd.helper.ChannelGroupHelper;
import ltd.util.RandomUtil;

public class MyChannelHandler extends ChannelInitializer<SocketChannel> {

	/** 连接通道被打开时 */
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		initChannel(ch, 4096);
		ch.pipeline().addLast(new MyServerHandler());
		//创建Session
		Session session = new Session();
		session.setChannel(ch);
		session.setSessionId(ch.id().toString() + RandomUtil.randomCreateSession());
		session.setIpAddress(ch.remoteAddress());
		session.setCreateDate(new Date());
		System.out.println("sessionID:" + session.getSessionId());
		//放入Map集合中
//		MyChannelGroup.getInstance().getSessionMap().put(ch.id().toString(), session);
		ChannelGroupHelper.putSession(ch.id().toString(), session);
	}
	
	protected void initChannel(SocketChannel ch, int len) throws Exception {
		initChannel(ch, len, 150, 30);
	}
	
	protected void initChannel(SocketChannel ch, int len, int readtime, int writetime) throws Exception {
		ch.pipeline().addLast(new IdleStateHandler(readtime, writetime, 0));
		
		// 设置定长解码器
		ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(len, 0, 4, 0, 4));

		// 设置空闲处理器
		ch.pipeline().addLast(new IdleHandler());

	}

}
